<?php
/**
 * Created by PhpStorm.
 * User: zhang
 * Date: 2018/4/29
 * Time: 13:44
 */
namespace app\account\model;

use app\common\model\Base;


class GetSMS extends Base{

    private $user_id_util;
    private $alidayu;


    function __construct(){
        parent::__construct();
        $this->user_id_util = new User_id_util();
    }

    /**
     *  判断操作发送短信的类型
     *  @param str $tel 电话号需要发送短信的电话号
     *  @param str $action 短信的操作类型（注册操作还是登陆操作）
     */
    function judgeSMSType($tel, $action) {
        if ($action === "REGISTER_ACCOUNT") {//注册
            if ($this->check->isPhoneExists($tel)) {
                echo echoJson(0, "电话号已存在!");
            } else {
                $this->sendVerificationCode($this->getSMSParam($tel, $action));
            }
        } else if ($action === "FIND_PASSWORD") {//找回密码
            if ($this->check->isfindTelExists($tel)) {
                $this->sendVerificationCode($this->getSMSParam($tel, $action));
            } else {
                echo echoJson(0, "电话号不存在!");
            }
        } else {

        }
    }


    /**
     *  得到发送短信的基本参数
     * @param str $tel 电话号需要发送短信的电话号
     * @param str $action 短信的操作类型（注册操作还是登陆操作）
     */
    function getSMSParam($tel, $action) {
        $dataTime = time();
        $rand = rand(100000, 999999);
        $data = array('code' => $rand, 'tel' => $tel, 'product' => '尚医道元',);
        if ($action === "REGISTER_ACCOUNT") {
            $data['type'] = "注册验证";
            $data['signName'] = "SMS_12880601";
            $data['sql'] = "INSERT INTO SMS_verification (tel,register_code,register_time) VALUES ('$tel',$rand,' $dataTime') "
                . "ON DUPLICATE KEY UPDATE register_code=$rand,register_time='$dataTime'";
        } else if ($action === "FIND_PASSWORD") {
            $data['type'] = "身份验证";
            $data['signName'] = "SMS_12880599";
            $data['sql'] = "INSERT INTO SMS_verification (tel,find_password_code,find_password_time) VALUES ('$tel',$rand,' $dataTime') "
                . "ON DUPLICATE KEY UPDATE find_password_code=$rand,find_password_time='$dataTime'";
        }
        return $data;
    }

    /**
     *  初始化发送短信的操作类型（注册操作还是登陆操作），且发送短信后判断短信是否发送成功
     * @param str $tel 电话号需要发送短信的电话号
     * @param str $action 短信的操作类型（注册操作还是登陆操作）
     */
    function sendVerificationCode($data) {
        $resp = $this->initVerificationCode($data);

        if (isset($resp->result->success) && $resp->result->success == "true") {//短信发送成功
            if ($this->mysql->insertSQL($data['sql'])) {
                echo echoJson(1, "短信发送成功!");
            } else {
                echo echoJson(0, "短信发送失败，请稍后再试!");
            }
        } else {
            isset($resp->sub_code) ? $msg = $this->alidayuErrCode($resp->sub_code) : $msg = "短信发送失败,错误代码_0002!";
            echo echoJson(0, $msg);
        }
    }

    /**
     * 初始化短信
     * @param str $tel 电话号需要发送短信的电话号
     * @param arr $data 需要发送的数据的值
     * @return json 短信发送的响应信息
     */
    function initVerificationCode($data) {
        //include_once '../api/alidayu/TopSdk.php';
        //exit;
        include EXTEND_PATH.'alidayu/TopSdk.php';
        $this->alidayu = new \TopClient;
        $this->alidayu->appkey = '24529079';
        $this->alidayu->secretKey = '32f236651cdedc29c6da33fb214c3d85';
        $req = new \AlibabaAliqinFcSmsNumSendRequest;
        $req->setSmsType("normal");
        $req->setSmsFreeSignName($data['type']);
        $req->setSmsParam('{"code":"' . $data['code'] . '","product":"' . $data['product'] . '"}');
        $req->setRecNum($data['tel']);
        $req->setSmsTemplateCode($data['signName']);
        $resp = $this->alidayu->execute($req);
        return $resp;
    }

    /**
     *  判断账号或密码是否为空
     * @param str $uid 账号
     * @param str $passd 密码
     * @return boolean
     */
    function alidayuErrCode($sub_code) {
        if ($sub_code == "isv.MOBILE_NUMBER_ILLEGAL") {
            return "短信发送失败，手机号码格式错误!";
        } else if ($sub_code == "isv.BUSINESS_LIMIT_CONTROL") {
            return "短信发送失败，短信发送条数超过限制！";
        } else if ($sub_code == "isv.SMS_SIGNATURE_ILLEGAL") {
            return "短信发送失败，签名不合法!";
        } else if ($sub_code == "isv.INVALID_PARAMETERS") {
            return "短信发送失败，参数异常!";
        } else {
            return "短信发送失败，错误代码_0001";
        }
    }
}